<!-- 字典项 -->
<template>
  <div class="app-container">
    <div class="search-bar mt-5">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="字典标签/字典值" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-[10px]">
        <el-button type="success" icon="plus" @click="handleAddRow">新增</el-button>
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button> -->
        <el-button type="primary" icon="check" :disabled="loading || !hasPendingChanges" @click="handleSaveAll">
          保存
        </el-button>
      </div>

      <el-table v-loading="loading" highlight-current-row :data="tableData" @selection-change="handleSelectionChange">
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="字典项标签" prop="label">
          <template #default="scope">
            <div v-if="scope.row.isEdit">
              <el-input v-model="scope.row.label" placeholder="请输入字典标签" />
            </div>
            <span v-else>{{ scope.row.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字典项值" prop="value">
          <template #default="scope">
            <div v-if="scope.row.isEdit">
              <el-input v-model="scope.row.value" placeholder="请输入字典值" />
            </div>
            <span v-else>{{ scope.row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="ordernum">
          <template #default="scope">
            <div v-if="scope.row.isEdit">
              <el-input-number v-model="scope.row.ordernum" controls-position="right" :min="0" />
            </div>
            <span v-else>{{ scope.row.ordernum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签类型" prop="tagType">
          <template #default="scope">
            <div v-if="scope.row.isEdit">
              <el-radio-group v-model="scope.row.tagType" size="small">
                <el-radio-button value="success">success</el-radio-button>
                <el-radio-button value="warning">warning</el-radio-button>
                <el-radio-button value="info">info</el-radio-button>
                <el-radio-button value="primary">primary</el-radio-button>
                <el-radio-button value="danger">danger</el-radio-button>
                <el-radio-button value="">无</el-radio-button>
              </el-radio-group>
            </div>
            <el-tag v-else-if="scope.row.tagType" :type="scope.row.tagType">
              {{ scope.row.tagType }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <template v-if="scope.row.isEdit">
              <el-button type="success" link size="small" icon="check" @click.stop="handleSaveRow(scope.row)">
                完成
              </el-button>
              <el-button type="info" link size="small" icon="close" @click.stop="handleCancelEdit(scope.row)">
                取消
              </el-button>
            </template>
            <template v-else>
              <el-button type="primary" link size="small" icon="edit" @click.stop="handleEditRow(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" link size="small" icon="delete" @click.stop="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DictItem",
  inherititems: false,
});

import DictAPI, { DictItemPageQuery, DictItemPageVO, DictItemForm } from "@/api/system/dict.api";

const route = useRoute();

const dictCode = ref(route.query.dictCode as string);

const queryFormRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictItemPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tableData = ref<Array<DictItemPageVO & { tagType?: DictItemForm['tagType'], isEdit?: boolean, originalData?: any, isNew?: boolean, dirty?: boolean }>>([]);
const hasPendingChanges = computed(() => tableData.value.some(row => row.isNew || row.isEdit || row.dirty));

// 查询
function handleQuery() {
  loading.value = true;
  queryParams.dictCode = dictCode.value
  DictAPI.getDictItemPage(dictCode.value, queryParams)
    .then((data) => {
      // 确保每行都有isEdit属性
      tableData.value = data.list.map(item => ({
        ...item,
        isEdit: false
      }));
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行选择
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 添加新行
function handleAddRow() {
  const newRow = {
    id: undefined as any,
    dictCode: dictCode.value,
    label: '',
    value: '',
    ordernum: 1,
    status: 1,
    tagType: '' as DictItemForm['tagType'],
    isEdit: true,
    isNew: true,
    dirty: true,
  };
  tableData.value.unshift(newRow as any);
}

// 编辑行
function handleEditRow(row: any) {
  row.originalData = JSON.parse(JSON.stringify(row));
  row.isEdit = true;
}

// 保存行
function handleSaveRow(row: any) {
  if (!row.label || !row.value) {
    ElMessage.warning("字典标签和字典值不能为空");
    return;
  }
  // 仅结束编辑并标记脏数据，不调用后端接口
  row.dictCode = dictCode.value;
  row.isEdit = false;
  row.dirty = true;
  delete row.originalData;
}

// 取消编辑
function handleCancelEdit(row: any) {
  if (row.isNew) {
    const index = tableData.value.findIndex(item => item === row);
    if (index !== -1) {
      tableData.value.splice(index, 1);
    }
  } else {
    if (row.originalData) {
      Object.assign(row, row.originalData);
    }
    row.isEdit = false;
    row.dirty = false;
    delete row.originalData;
  }
}
// 批量保存全部更改
async function handleSaveAll() {
  if (!hasPendingChanges.value) {
    ElMessage.info("没有需要保存的更改");
    return;
  }
  loading.value = true;
  try {
    const payloadList: DictItemForm[] = tableData.value.map(row => ({
      id: row.id as any,
      dictCode: dictCode.value,
      label: row.label,
      value: row.value,
      ordernum: row.ordernum,
      status: row.status ?? 1,
      tagType: row.tagType,
    }));
    await DictAPI.saveDictItems(dictCode.value, payloadList);
    ElMessage.success("保存成功");
    await handleQuery();
    tableData.value = tableData.value.map(r => ({ ...r, isEdit: false, isNew: false, dirty: false, originalData: undefined }));
  } catch (e) {
    ElMessage.error("保存失败，请重试");
  } finally {
    loading.value = false;
  }
}

/**
 * 删除字典
 *
 * @param id 字典ID
 */
function handleDelete(row?: any) {
  if (row) {
    const idx = tableData.value.findIndex(item => item === row || String(item.id) === String(row.id));
    if (idx !== -1) {
      tableData.value.splice(idx, 1);
      ElMessage.success("已删除该行");
    } else {
      ElMessage.warning("未找到该行");
    }
    return;
  }

  if (!ids.value || ids.value.length === 0) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  const selectedIdSet = new Set(ids.value.map((v: any) => String(v)));
  const before = tableData.value.length;
  tableData.value = tableData.value.filter(item => !selectedIdSet.has(String(item.id)));
  ids.value = [];
  const deleted = before - tableData.value.length;
  if (deleted > 0) {
    ElMessage.success(`已删除${deleted}行`);
  } else {
    ElMessage.info("未删除任何行");
  }
}

onMounted(() => {
  handleQuery();
});

// 同一路由参数变化时更新数据
onBeforeRouteUpdate((to) => {
  queryParams.dictCode = to.query.dictCode as string;
  handleQuery();
});
</script>
